package com.xthh;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.luck.picture.lib.broadcast.BroadcastManager;
import com.xt.pro.BLEControlJni;
import com.xt.pro.BleNFCBindInfo;
import com.xthh._enum.HH_EnumErrorCode;
import com.xthh._enum.HH_EnumNfcErrorCode;
import com.xthh._function.HH_CharUtil;
import com.xthh._function.HH_Logging;
import com.xthh._function.HH_SystemUtil;
import com.xthh._struct.HH_T_SystemParams;

import java.io.IOException;
import java.util.Arrays;

public abstract class XTBaseNFCActivity  extends AppCompatActivity {
    private static final String TAG = "XTBaseNFCActivity";
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    public Handler handlerBaseNfc;
    public final int MSG_NFC_STATE = 2001;
    public HH_T_SystemParams systemParams;
    boolean bIsNfcCloseInfo = false;
    private boolean bAutoNfcClose = false;

    @Override
    protected void onStart() {
        super.onStart();
        if (!hasNfc(this)) {
            HH_SystemUtil.SendMessage(new HH_T_SystemParams(null, null, handlerBaseNfc), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.DISABLE.ordinal());
        }

        if (mNfcAdapter != null) {
            int flag = 0;
            mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), flag);
        }
    }

    String ReadNfcInfo(Tag tag){
        if (tag == null) {
            HH_SystemUtil.SendMessage(new HH_T_SystemParams(null, null, handlerBaseNfc), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.ABNORMAL_TAG.ordinal());
            return null;
        }


        /*String[] techList = tag.getTechList();
        if (techList != null){
            for (int i = 0; i < techList.length; i++){
                HH_Logging.i(TAG, "tech=%s(%d-%d)", techList[i], i, techList.length);
            }
        }*/



        String sMac = null;
        Ndef isoDep = Ndef.get(tag);
        if (isoDep != null) {
            try {
                if (!isoDep.isConnected()) {
                    isoDep.connect();
                }

                NdefMessage ndefReadMessage = null;
                try {
                    ndefReadMessage = isoDep.getNdefMessage();
                } catch (FormatException e) {

                } catch (IOException e) {

                }
                if (ndefReadMessage != null) {
                    NdefRecord nrArray[] = ndefReadMessage.getRecords();
                    String sReadAll = "";
                    for (int i = 0; i < nrArray.length; i++) {
                        NdefRecord record = nrArray[i];

                        byte bRecvOrder[] = parseTextRecord(record);
                        sReadAll = new String(bRecvOrder);
                        if (sReadAll != null && sReadAll.length() > 0)
                            break;
                    }

                    byte []bNfcInfo = HH_CharUtil.StringToByte2(sReadAll, "GB2312");
                    BleNFCBindInfo nfcInfo = BLEControlJni.GetBleNFCBindInfo(bNfcInfo, bNfcInfo.length);

                    if (nfcInfo != null && nfcInfo.mac.length() == 12){
                        if (nfcInfo.customSN == null)
                            nfcInfo.customSN = "";
                        if (nfcInfo.customSRRC == null)
                            nfcInfo.customSRRC = "";
                        if (nfcInfo.customerCode == null)
                            nfcInfo.customerCode = "";
                        // 返回绑定成功
                        sMac = nfcInfo.mac;
                        HH_SystemUtil.SendMessage(new HH_T_SystemParams(null, null, handlerBaseNfc), MSG_NFC_STATE, nfcInfo, 0, HH_EnumNfcErrorCode.BIND_INFO.ordinal());
                    } else {
                        HH_SystemUtil.SendMessage(new HH_T_SystemParams(null, null, handlerBaseNfc), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.ABNORMAL_DATA.ordinal());
                    }
                }
            } catch (Exception e) {
                HH_SystemUtil.SendMessage(new HH_T_SystemParams(null, null, handlerBaseNfc), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.INCOMPATIBLE_TAG.ordinal());
            } finally {
                try {
                    isoDep.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sMac;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Tag tag = intent.getExtras().getParcelable(NfcAdapter.EXTRA_TAG);
        String mac = ReadNfcInfo(tag);

        if (bAutoNfcClose){
            if (mac != null && mac.length() == 12){

                if (!bIsNfcCloseInfo){
                    HH_Logging.i(TAG, "正在处理断电任务");
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                bIsNfcCloseInfo = true;
                                HH_EnumErrorCode code = XTCore.NFCClose(systemParams, mac, "");
                                bIsNfcCloseInfo = false;
                                HH_Logging.i(TAG, "断电完成");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                } else {
                    HH_Logging.i(TAG, "断电未结束");
                }
            }
        }

    }

    public static byte[] parseTextRecord(NdefRecord ndefRecord) {

        //判断TNF
        if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
            return null;
        }
        //判断可变的长度的类型
        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            return null;
        }
        try {
            //获得字节数组，然后进行分析
            byte[] payload = ndefRecord.getPayload();
            return payload;
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mNfcAdapter != null && mPendingIntent != null) {
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mNfcAdapter != null) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public boolean hasNfc(Activity context) {
        NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
        mNfcAdapter = manager.getDefaultAdapter();
        if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
            return true;
        }
        return false;
    }


    public void GetNFCCardInfo(HH_T_SystemParams sp, boolean autoNfcClose){
        systemParams = sp;
        bAutoNfcClose = autoNfcClose;

        if (mNfcAdapter != null){
            mNfcAdapter.disableReaderMode(this);
        }
    }

    public void startReaderMode() {
        Activity act = this;
        Bundle bundle = new Bundle();
        bundle.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 500);
        mNfcAdapter.enableReaderMode(this, new NfcAdapter.ReaderCallback() {
            @Override
            public void onTagDiscovered(Tag tag) {
                ReadNfcInfo(tag);
            }

        }, NfcAdapter.FLAG_READER_NFC_A,  bundle);
    }
}
